package com.gamewithpurpose.dbinterface;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.gamewithpurpose.dbinterface.POJO.User;

public class UserDAO {
	/* 
	 * Add a new entry
	 */
	public static Integer addUser(String user) {
		Session session = DBFactory.getSessionFactory().openSession();
		Transaction tx = null;
		Integer id = null;
		
		try {
			tx = session.beginTransaction();
			User pojo = new User(user);
			id = (Integer) session.save(pojo);
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return id;
	}

	/*
	 * Get all users
	 */
	public static List<User> list() {
		Session session = DBFactory.getSessionFactory().openSession();
		Transaction tx = null;
		List<User> Users = null;
		
		try {
			tx = session.beginTransaction();
			Users = session.createQuery("FROM User").list();
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		
		return Users;
	}
	
	/*
	 * Get if a user exists or not. 
	 */
	public static boolean isExist(String phrase) {
		Session session = DBFactory.getSessionFactory().openSession();
		Transaction tx = null;
		Long res = 0L;
		
		try {
			tx = session.beginTransaction();
			String query = String.format("select count(*) FROM "
										 + "User where phrase='%s'", phrase);
			res = (Long) session.createQuery(query).uniqueResult();
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		
		return (res > 0 ? true : false);
	}
	
	/*
	 * Delete a user with id
	 */
	public static void delete(int id) {
		Session session = DBFactory.getSessionFactory().openSession();
		Transaction tx = null;
		
		try {
			tx = session.beginTransaction();
			User pojo = (User) session.get(User.class, id);
			session.delete(pojo);
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}
	
	/*
	 * Delete all users and return the number of deleted entries.
	 */
	public static int deleteAll() {
		Session session = DBFactory.getSessionFactory().openSession();
		Transaction tx = null;
		int res = 0;
		
		try {
			tx = session.beginTransaction();
			res = session.createQuery("delete FROM User").executeUpdate();
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		
		return res;
	}
}
